package com.apes.fn.scm.internal.help.service.voucher.inner;

import com.apes.fn.scm.internal.help.model.InternalHelpReturnApproval;
import com.apes.fn.scm.internal.help.model.InternalHelpReturnApprovalItem;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.util.MapUtil;
import com.apes.scm.sal.saleOrder.SaleOrder;
import com.apes.scm.sal.saleOrder.SaleOrderItem;
import com.apes.scm.sal.saleOrder.SaleOrderItemRepository;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.repository.VoucherItemRepository;
import com.apes.scm.voucher.repository.VoucherRepository;
import com.apes.scm.voucher.service.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 内协跨公司凭证退回
 *
 * @Author wuq
 * @Date 2021-11-4
 */
@Service
public class InnerHelpReturnVoucherService extends DomainService {

    @Autowired
    private VoucherItemRepository voucherItemRepository;

    public void process(InternalHelpReturnApproval internalHelpReturnApproval) {

        // 由于会存在多个分销单（正常库与带安库分开），需要把所有的分销单找出来
        List<SaleOrderItem> saleOrderItems = internalHelpReturnApproval.getApprovalItems().stream().map( this::getSaleOrderItem ).collect(Collectors.toList());
        saleOrderItems.stream().collect(Collectors.groupingBy(SaleOrderItem::getSaleOrder)).forEach(
                (saleOrder, orderItems) -> {
                    Voucher voucher = new Voucher();
                    voucher.setReturned(true);
                    voucher.setBusinessType(BusinessType.SALE_RETURN);

                    voucher.setCompany(internalHelpReturnApproval.getReceiptLocation().getCompany());
                    voucher.setPartner(internalHelpReturnApproval.getShipLocation().getCompany().getParty().getPatyRoleByType("Customer"));
                    voucher.setClerk(internalHelpReturnApproval.getApplyUid());

                    voucher.setDept(saleOrder.getDept());
                    voucher.setContract(saleOrder.getContract());

                    voucher.setInventoryMode(saleOrder.getCooperation().getInventoryMode());        // 设置库存模式：自有
                    // 核算方式：按采购价核算
                    voucher.setAccountingMethod(saleOrder.getCooperation().getAccountingMethod());
                    voucher.setScene(internalHelpReturnApproval.getScene());
                    voucher.setOrigin(internalHelpReturnApproval.getId());
                    voucher.setOriginBusinessType(internalHelpReturnApproval.getInnerBusinessType());
                    voucher.setSource(internalHelpReturnApproval.getId());
                    voucher.setSourceBusinessType(internalHelpReturnApproval.getInnerBusinessType());
                    voucher.setCustomerExpand(internalHelpReturnApproval.getCustomerExpand().getId());

                    // 获取原分销单凭证
                    Voucher originSaleVoucher = SpringManager.getBean(VoucherRepository.class)
                            .findOne(JpaDsl.toCriteriaByEq("sourceBusinessType", SaleOrder.class.getSimpleName(),
                                    "source", saleOrder.getId(), "voucherType", "CUSTOMER_SALE")).orElse(null);
                    Optional.ofNullable(originSaleVoucher).orElseThrow(() -> new RuntimeException("没有找到分销原单：" + saleOrder.getId() + " 的业务凭证！"));

                    voucher.setVoucherItems(
                            orderItems.stream().map(
                                    item -> {
                                        VoucherItem voucherItem = new VoucherItem();
                                        voucherItem.setProduct(item.getProduct());
                                        voucherItem.setOwner(internalHelpReturnApproval.getReceiptLocation().getCompany());
                                        voucherItem.setOriginItemId(String.valueOf(item.getId()));
                                        voucherItem.setSourceItemId(String.valueOf(item.getId()));
                                        voucherItem.setUom(item.getUom());

                                        // 获取退货数量
                                        InternalHelpReturnApprovalItem tempItem =  internalHelpReturnApproval.getApprovalItems().stream()
                                                .filter( approvalItem -> approvalItem.getOriginItemId().equals(item.getId())).findFirst().get();
                                        voucherItem.setProductQty(-1.00 * tempItem.getProductReturnQty());

                                        //获取分销凭证明细
                                        VoucherItem saleVoucherItem = voucherItemRepository.findOne(JpaDsl.toCriteriaByEq("sourceItemId", item.getId(), "voucher", originSaleVoucher))
                                                .orElseThrow(() -> new RuntimeException(String.format("未找到对应的销售凭证，分销明细行号[%s]", item.getId())));
                                        voucherItem.setVoucherItem(saleVoucherItem);

                                        voucherItem.setPriceUnit(saleVoucherItem.getPriceUnit());   // 重新赋值单价与税率
                                        voucherItem.setTax(saleVoucherItem.getTax());
                                        return voucherItem;
                                    }).collect(Collectors.toSet()));


                    Voucher newVoucher = invoke("voucher.create", MapUtil.mapped(voucher));
                    invoke("invoice.create", MapUtil.mapped(invoke("voucher.flow.invoice", MapUtil.mapped(newVoucher))));
                });
    }

    private SaleOrderItem getSaleOrderItem(InternalHelpReturnApprovalItem approvalItem) {
        return SpringManager.getBean(SaleOrderItemRepository.class).findOne(approvalItem.getOriginItemId());
    }
}
